package com.monitor.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.monitor.entity.*;
import com.monitor.service.*;
import com.monitor.util.ReadExcel;
import com.monitor.util.Result;
import com.monitor.util.WDWUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 物料流转物料表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-08
 */
@RestController
@RequestMapping("/erpMaterielFlowMateriel")
@Api(description="物料流转物料")
public class ErpMaterielFlowMaterielController {


    @Value("${web.upload-path}")
    private String path;

    @Resource
    private ErpMaterielFlowMaterielService materielFlowMaterielService;
    @Autowired
    private ErpTpmsTireInformationService erpTpmsTireInformationService;
    @Resource
    private ErpCustomerWarehouseService warehouseService;
    @Resource
    private ErpWarehouseService erpWarehouseService;
    @Resource
    private ErpMaterielService materielService;

    @RequestMapping("/inertOrUpdateFlowMateriel")
    @ApiOperation("添加Or修改物料属性--期初物料")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "invoiceType", value = "发票类型", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "file", value = "生产编号文档", required = false, dataType = "file", paramType = "query"),
            @ApiImplicitParam(name = "allNumber", value = "数量", required = false, dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "allPrice", value = "总金额", required = false, dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "price", value = "单价", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pid", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<Integer> inertOrUpdateFlowMateriel(ErpMaterielFlowMateriel flowMateriel, Integer pid,@RequestParam(value="file") MultipartFile file,
                                              HttpServletRequest request, HttpServletResponse response,Integer allNumber,Double allPrice,Double price,String invoiceType) {
        Result<Integer> result = new Result<Integer>();
        try {
            ErpMaterielFlowMateriel flowMateriel1=materielFlowMaterielService.getmaterielByPro(flowMateriel);
            if(flowMateriel1==null){
                ErpTpmsTireInformation information=erpTpmsTireInformationService.selectOne(new EntityWrapper<ErpTpmsTireInformation>().eq("brand",flowMateriel.getMaterielBrand()).and().eq("specifications",flowMateriel.getMaterielSpecifications()).and().eq("model",flowMateriel.getMaterielModel()).and().eq("place",flowMateriel.getMaterielPlace()));
                if(information==null){
                    information=new ErpTpmsTireInformation();
                    information.setPid(pid);
                    information.setBrand(flowMateriel.getMaterielBrand());
                    information.setSpecifications(flowMateriel.getMaterielSpecifications());
                    information.setModel(flowMateriel.getMaterielModel());
                    information.setPlace(flowMateriel.getMaterielPlace());
                    erpTpmsTireInformationService.insert(information);
                }
                flowMateriel.setInformationId(information.getId());
                materielFlowMaterielService.insert(flowMateriel);
            }
            ErpCustomerWarehouse customerWarehouse=warehouseService.selectOne(new EntityWrapper<ErpCustomerWarehouse>().eq("customer_id",pid));
            ErpWarehouse warehouse=new ErpWarehouse();
            //warehouse.setMaterielWarnAmount();
            //warehouse.setMaterielTax(price);
            //warehouse.setMaterielOccupyNumber();
            //warehouse.setMaterielNotax();
            warehouse.setMaterielNumber(allNumber);
            warehouse.setWarehouseId(customerWarehouse.getId());
            warehouse.setMaterielName(flowMateriel.getMaterielName());
            warehouse.setMaterielBrand(flowMateriel.getMaterielBrand());
            warehouse.setCustomerId(pid);
            warehouse.setMaterielSpecifications(flowMateriel.getMaterielSpecifications());
            warehouse.setMaterielModel(flowMateriel.getMaterielModel());
            warehouse.setMaterielPlace(flowMateriel.getMaterielPlace());
            warehouse.setMaterielState(flowMateriel.getMaterielState());
            warehouse.setMaterielUnit(flowMateriel.getMaterielUnit());
            warehouse.setAllPrice(allPrice);
            warehouse.setMaterielId(flowMateriel.getId());
            warehouse.setInvoiceType(invoiceType);
            erpWarehouseService.insert(warehouse);

            if(file==null){
                result.setCount(0);
                result.setCode(1);
                result.setData(null);
                result.setMsg("文件是为空！");
                return result;
            }

            //获取文件名
            String name=file.getOriginalFilename();

            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
            long size=file.getSize();
            if(name==null || ("").equals(name) && size==0 && !WDWUtil.validateExcel(name)){
                result.setCount(0);
                result.setCode(1);
                result.setData(null);
                result.setMsg("文件格式不正确！请使用.xls或.xlsx后缀文档。");
                return result;
            }

            Boolean b=false;
            //创建处理EXCEL
            ReadExcel readExcel=new ReadExcel();
            //解析excel，获取客户信息集合。
            List<List<Object>> customerList = readExcel.getExcelInfo(path,file,request);
            if(customerList != null && !customerList.toString().equals("[]") && customerList.size()>=1){
                b = true;
            }
            List<ErpMateriel> materielList=new ArrayList<ErpMateriel>();
            if(b){
                customerList.stream().forEach(number -> {
                    ErpMateriel materiel=new ErpMateriel();
                    materiel.setWarehouseId(warehouse.getId());
                    materiel.setMaterielProductionId(number.get(0).toString());//生产编号
                    materiel.setMaterielFlowId(flowMateriel.getId());
                    materiel.setMaterielId(flowMateriel.getId());
                    //materiel.setMaterielNumber();
                    materiel.setMaterielBrand(flowMateriel.getMaterielBrand());
                    //materiel.setMaterielDot();
                    //materiel.setMaterielLoad();
                    materiel.setMaterielModel(flowMateriel.getMaterielModel());
                    materiel.setMaterielName(flowMateriel.getMaterielName());
                    //materiel.setMaterielRefurbished();
                    materiel.setMaterielState(flowMateriel.getMaterielState());
                    materiel.setDelectType(1);
                    materiel.setState(1);
                    materiel.setMaterielUnit(flowMateriel.getMaterielUnit());
                    materiel.setMaterielStoragePrice(price);
                    materiel.setQichutype("期初");
                    materiel.setKucunorliucun("库存");
                    materielList.add(materiel);
                });
            }
            materielService.insertBatch(materielList);

            result.setCount(1);
            result.setData(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/getMaterielByMaterielId")
    @ApiOperation("根据仓库id仓库物料信息")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "materielId", value = "物料ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<ErpMaterielFlowMateriel> getWarehouseByWarehouseId(Integer materielId) {
        Result<ErpMaterielFlowMateriel> result=new Result<ErpMaterielFlowMateriel>();
        try{
            result.setCount(1);
            result.setData(materielFlowMaterielService.selectById(materielId));
        }catch (Exception e){e.printStackTrace();}
        return result;
    }

    @RequestMapping("/getMaterielList")
    @ApiOperation("根据仓库物料信息")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "materielId", value = "物料ID", required = false, dataType = "int", paramType = "query")*/
    })
    public @ResponseBody
    Result<List<ErpMaterielFlowMateriel>> getMaterielList() {
        Result<List<ErpMaterielFlowMateriel>> result=new Result<List<ErpMaterielFlowMateriel>>();
        try{
            result.setCount(1);
            result.setData(materielFlowMaterielService.selectList(new EntityWrapper<ErpMaterielFlowMateriel>()));
        }catch (Exception e){e.printStackTrace();}
        return result;
    }


    @RequestMapping("/getMaterielListPage")
    @ApiOperation("根据客户ID查询用户分页")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")*/
    })
    public @ResponseBody
    Result<Page<ErpMaterielFlowMateriel>> getMaterielListPage(@RequestParam(value = "page", defaultValue = "1") int page,
                                              @RequestParam(value="limit",defaultValue="10") int limit, Integer custId) {
        Result<Page<ErpMaterielFlowMateriel>> result=new Result<Page<ErpMaterielFlowMateriel>>();
        try{
            Page<ErpMaterielFlowMateriel> page1=new Page<ErpMaterielFlowMateriel>(page,limit);
            Page<ErpMaterielFlowMateriel> carPage=materielFlowMaterielService.selectPage(page1,new EntityWrapper<ErpMaterielFlowMateriel>());
            //Page<ErpCustomerCar> page=new Page<ErpCustomerCar>(1,2);
            result.setCount(carPage.getRecords().size());
            result.setData(carPage);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }
























}

